package com.example.usbcamera;

import android.app.Activity;
import android.widget.FrameLayout;
import android.view.ViewGroup;
import com.alibaba.fastjson.JSONObject;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;


public class CameraXModule extends UniModule {
    private CameraXView cameraXView;

    @UniJSMethod(uiThread = true)
    public void startPreview(JSONObject options, UniJSCallback callback) {
        Activity activity = (Activity) mUniSDKInstance.getContext();

        int width = options.getIntValue("width");
        int height = options.getIntValue("height");
        int left = options.getIntValue("left");
        int top = options.getIntValue("top");

        cameraXView = new CameraXView(activity);

        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(width, height);
        layoutParams.leftMargin = left;
        layoutParams.topMargin = top;

        activity.addContentView(cameraXView, layoutParams);
        callback.invoke("Camera preview started");
    }

    @UniJSMethod(uiThread = true)
    public void takePhoto(UniJSCallback callback) {
        if (cameraXView != null) {
            cameraXView.takePicture(base64 -> {
                JSONObject result = new JSONObject();
                result.put("base64", base64);
                callback.invoke(result);
            });
        }
    }

    @UniJSMethod(uiThread = true)
    public void stopPreview(UniJSCallback callback) {
        if (cameraXView != null && cameraXView.getParent() != null) {
            ((ViewGroup) cameraXView.getParent()).removeView(cameraXView);
            cameraXView = null;
        }
        callback.invoke("CameraX stopped");
    }
}
